package xyz.itpath.oss.aliyun.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;
import xyz.itpath.config.OssProperties;
import xyz.itpath.service.OssService;

import java.io.InputStream;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;

/**
 * @author zhaomengru
 * create by 2024/1/3 - 21:13
 */
@Service
@RequiredArgsConstructor
@ConditionalOnMissingBean(OssService.class)
public class OssServiceImpl implements OssService {

    private String bucketName;
    private final OSS ossClient;

    @PostConstruct
    public void init(OssProperties properties) {
        bucketName = properties.getBucketName();
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, inputStream);
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
        return putObjectResult.getETag();
    }

    @Override
    public InputStream download(String path) {
        return ossClient.getObject(bucketName, path).getObjectContent();
    }

    @Override
    public void delete(String path) {
        ossClient.deleteObject(bucketName, path);
    }

    @Override
    public String getUrl(String path, Duration duration) {
        return ossClient.generatePresignedUrl(bucketName, path, Date.from(Instant.now().plus(duration))).toString();
    }
}
